﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Things.Bar;
using Things.Bar.Models;

namespace Things.Web.Bar
{
    public partial class AddNotice : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                NoticeTypeRepository rep = new NoticeTypeRepository();
                List<NoticeType> types = rep.FindAll();
                _ctlListType.DataSource = types;
                _ctlListType.DataBind();

                BindData();
            }
        }

        protected Notice GetModel()
        {
            Notice model =null;
            if (string.IsNullOrEmpty(Request["noticeid"]) == false)
            {
                Guid id = new Guid(Request["noticeid"]);
                NoticeRepository rep = new NoticeRepository();
                model = rep.Find(id);
            }
            return model;
        }

        protected void BindData()
        {
            Notice model = GetModel();
            if (model != null)
            {
                _ctlEditTitle.Text = model.Title;
                _ctlContent.Text = model.Content;
                _ctlEditImg.Text = model.ImgUrl;
                _ctlEditDescription.Text = model.Description;
                _ctlListType.SelectedValue = model.TypeId.ToString();
            }

        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            Notice notice = GetModel();
            if (notice == null)
            {
                notice = new Notice();
            }
            notice.Title = _ctlEditTitle.Text;
            notice.IsAllowReply = false;
            notice.CreatedTime = DateTime.Now;
            notice.Author = "谷吧";
            notice.Content = _ctlContent.Text;
            notice.Description = _ctlEditDescription.Text;
            notice.ImgUrl = _ctlEditImg.Text;
            notice.TypeId = new Guid(_ctlListType.SelectedValue);

            if (notice.Id == Guid.Empty)
            {
                // add
                notice.Id = Guid.NewGuid();
                if (new NoticeRepository().Restore(notice))
                {
                    Response.Redirect("./NoticeList.aspx");
                }
            }
            else
            {
                // update
                if (new NoticeRepository().Update(notice))
                {
                    Response.Redirect("./NoticeList.aspx");
                }
            }
            
        }

        protected void _ctlBtnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect("./NoticeList.aspx");
        }
    }
}